package api

import (
	"context"
	"net/http"
	"sdc/repository/db/dao"
	"sdc/repository/db/model"
	"sdc/service"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 新增分类
func CreateCategory(c *gin.Context) {
	var req struct {
		Name string `json:"name" binding:"required"`
		Sort int    `json:"sort" binding:"gte=0"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	db := dao.NewDBClient(context.Background())
	service := service.NewCategoryService(db)
	if err := service.CreateCategory(&model.Category{
		Name: req.Name,
		Sort: req.Sort,
	}); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "创建分类失败",
		})
	}
}

// ListCategories 获取分类列表
func ListCategories(c *gin.Context) {
	db := dao.NewDBClient(context.Background())
	service := service.NewCategoryService(db)
	categories, err := service.ListCategories()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "获取分类列表失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": categories,
	})
}

// UpdateCategory 更新分类
func UpdateCategory(c *gin.Context) {
	categoryID, _ := strconv.ParseUint(c.Param("id"), 10, 64)

	var req struct {
		Name   string `json:"name" binding:"required"`
		Sort   int    `json:"sort" binding:"gte=0"`
		Status int8   `json:"status" binding:"oneof=0 1"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	category := &model.Category{
		ID:     uint(categoryID),
		Name:   req.Name,
		Sort:   req.Sort,
		Status: req.Status,
	}

	db := dao.NewDBClient(context.Background())
	service := service.NewCategoryService(db)
	if err := service.UpdateCategory(category); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "更新失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "更新成功",
	})
}

// DeleteCategory 删除分类
func DeleteCategory(c *gin.Context) {
	categoryID, _ := strconv.ParseUint(c.Param("id"), 10, 64)

	db := dao.NewDBClient(context.Background())
	service := service.NewAdminService(db)
	if err := service.DeleteCategory(categoryID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
	}
}
